import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { CompanyService } from "src/modules/company/company.service";
import { dateNewFirst } from "src/utils/util";
import { Repository } from "typeorm";
import { Bank } from "./bank.entity";
import { CreateBankDto } from "./dto/create-bank.dto";

@Injectable()
export class BankService {
  constructor(
    @InjectRepository(Bank)
    private readonly bankRepository: Repository<Bank>,
    private readonly companyService: CompanyService
  ) {}
  async findAll(): Promise<Bank[]> {
    return (await this.bankRepository.find()).sort(dateNewFirst);
  }
  async findByCompany(companyId: string): Promise<Bank[]> {
    const company = await this.companyService.find(companyId);
    return (
      await this.bankRepository.find({
        company,
      })
    ).sort(dateNewFirst);
  }
  find(id: string): Promise<Bank> {
    return this.bankRepository.findOneOrFail(id);
  }
  findOneWithCompany(id: string): Promise<Bank> {
    return this.bankRepository.findOneOrFail(id, {
      relations: ["company"],
    });
  }
  async create(createBankDto: CreateBankDto, companyId: string): Promise<Bank> {
    const bank = new Bank();
    const company = await this.companyService.find(companyId);
    Object.assign(bank, createBankDto, { company });
    return this.bankRepository.save(bank);
  }
  async remove(id: string): Promise<Bank> {
    const bank = await this.find(id);
    return await this.bankRepository.remove(bank);
  }
}
